/*
 * Delete directories recursively
 *
 * Copyright 2023 Odin Kroeger.
 *
 * This file is part of suCGI.
 *
 * suCGI is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Affero General Public License as published
 * by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * suCGI is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General
 * Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with suCGI. If not, see <https://www.gnu.org/licenses/>.
 */

#define _XOPEN_SOURCE 700

#include <sys/wait.h>
#include <assert.h>
#include <err.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "dir.h"
#include "types.h"

int
dir_tree_rm(const char *const fname, const ErrorFn errh)
{
    assert(fname != NULL);
    assert(*fname != '\0');
    assert(strncmp(fname, "/", sizeof("/")) != 0);

    errno = 0;
    int retval = dir_walk(fname, remove, ORDER_POST, NULL);
    if (retval == 0) {
        return 0;
    }

    /*
     * Calling rm -rf ain't pretty, but it's worth a shot.
     * On some systems, it succeeds even when dir_walk fails.
     */

    errno = 0;
    /* RATS: ignore; the test suite is not privy to sensitive data */
    const int pid = fork();
    if (pid < 0) {
        if (errh != NULL) {
            errh(EXIT_FAILURE, "fork");
        }

        return -1;
    }

    errno = 0;
    if (pid == 0) {
        /* RATS: ignore; safe enough */
        (void) execlp("rm", "rm", "-rf", fname, NULL);
        /* cppcheck-suppress unreachableCode; reached if execlp fails */
        err(EXIT_FAILURE, "execlp rm");
    }

    int status = 0;
    errno = 0;
    retval = waitpid(pid, &status, 0);
    if (retval == -1) {
        if (errh != NULL) {
            errh(EXIT_FAILURE, "waitpid %d", pid);
        }

        return -1;
    }

    if (status != 0) {
        if (errh != NULL) {
            errh(EXIT_FAILURE, "rm -rf %s: Exited with status %d",
                 fname, WEXITSTATUS(status));
        }

        return -1;
    }

    return 0;
}
